import axios from 'axios'
// import Vue from 'vue'
import Vue from 'vue'
import router from '../router/index'
const http = axios.create({
  baseURL: 'http://localhost:3000/api/admin',
})

http.interceptors.request.use(config => {
  //为每一个请求头加上token
  if (sessionStorage.getItem('token')) {
    config.headers.Authorization = 'Bearer ' + sessionStorage.getItem('token')
  }
  return config
}, err => {
  return Promise.reject(err)
})
// 通用的错误处理
http.interceptors.response.use(res => {
  return res
}, err => {
  if (err.response.data.message) {
    Vue.prototype.$message({ message: err.response.data.message, type: 'error' })
  }
  if (err.response.status === 422) {
    router.push('/login')
  }
  // 一个给定原因了的被拒绝的 Promise
  // Vue.prototype.$message({ message: err.response.data.message, type: 'error' })
  return Promise.reject(err)
})

export default http